#  -*- coding: utf-8 -*-

"""
对比basic表和daily表中的PE值
"""

from database import DB_CONN
import pandas as pd

def compare_pe_values(limit=10):
    """
    对比basic表和daily表中的PE值
    
    :param limit: 限制对比的记录数量，用于测试
    """
    print("=== PE值对比分析 ===\n")
    
    # 获取basic表中有PE值的记录（随机取一些样本）
    basic_records = list(DB_CONN.basic.find(
        {"pe": {"$gt": 0}},  # PE大于0的记录
        {"code": 1, "date": 1, "pe": 1, "_id": 0}
    ).limit(limit))
    
    print(f"从basic表获取了 {len(basic_records)} 条有PE值的记录")
    
    comparison_results = []
    match_count = 0
    mismatch_count = 0
    daily_no_pe_count = 0
    
    for basic_record in basic_records:
        code = basic_record['code']
        date = basic_record['date']
        basic_pe = basic_record['pe']
        
        # 在daily表中查找对应的记录
        daily_record = DB_CONN.daily.find_one(
            {"code": code, "date": date},
            {"pe": 1, "_id": 0}
        )
        
        if daily_record:
            daily_pe = daily_record.get('pe', None)
            
            if daily_pe is None:
                # daily表中没有PE值
                daily_no_pe_count += 1
                status = "daily表无PE"
                pe_diff = "N/A"
            elif abs(basic_pe - daily_pe) < 0.001:  # 考虑浮点数精度
                # PE值匹配
                match_count += 1
                status = "匹配"
                pe_diff = 0
            else:
                # PE值不匹配
                mismatch_count += 1
                status = "不匹配"
                pe_diff = round(abs(basic_pe - daily_pe), 4)
                
            comparison_results.append({
                'code': code,
                'date': date,
                'basic_pe': round(basic_pe, 4),
                'daily_pe': round(daily_pe, 4) if daily_pe else None,
                'difference': pe_diff,
                'status': status
            })
            
        else:
            # daily表中没有对应记录
            comparison_results.append({
                'code': code,
                'date': date,
                'basic_pe': round(basic_pe, 4),
                'daily_pe': None,
                'difference': "N/A",
                'status': "daily表无记录"
            })
    
    # 显示对比结果
    print("\n=== 详细对比结果 ===")
    print(f"{'代码':<8} {'日期':<12} {'Basic PE':<10} {'Daily PE':<10} {'差异':<8} {'状态'}")
    print("-" * 65)
    
    for result in comparison_results[:20]:  # 只显示前20条
        print(f"{result['code']:<8} {result['date']:<12} {result['basic_pe']:<10} "
              f"{result['daily_pe'] or 'None':<10} {result['difference']:<8} {result['status']}")
    
    # 统计摘要
    print(f"\n=== 统计摘要 ===")
    print(f"总对比记录数: {len(comparison_results)}")
    print(f"PE值匹配: {match_count} 条")
    print(f"PE值不匹配: {mismatch_count} 条")
    print(f"Daily表无PE值: {daily_no_pe_count} 条")
    print(f"Daily表无对应记录: {len(comparison_results) - match_count - mismatch_count - daily_no_pe_count} 条")
    
    if len(comparison_results) > 0:
        match_rate = (match_count / len(comparison_results)) * 100
        print(f"匹配率: {match_rate:.1f}%")
    
    # 如果有不匹配的，显示具体情况
    if mismatch_count > 0:
        print(f"\n=== 不匹配的记录详情 ===")
        mismatches = [r for r in comparison_results if r['status'] == '不匹配']
        for mismatch in mismatches[:5]:  # 只显示前5个不匹配的
            print(f"股票 {mismatch['code']} 在 {mismatch['date']}: "
                  f"Basic PE={mismatch['basic_pe']}, Daily PE={mismatch['daily_pe']}, "
                  f"差异={mismatch['difference']}")


def check_pe_data_distribution():
    """
    检查两个表中PE数据的分布情况
    """
    print("\n=== PE数据分布检查 ===")
    
    # Basic表PE分布
    basic_total = DB_CONN.basic.count_documents({})
    basic_with_pe = DB_CONN.basic.count_documents({"pe": {"$gt": 0}})
    basic_zero_pe = DB_CONN.basic.count_documents({"pe": 0})
    
    print(f"Basic表:")
    print(f"  总记录数: {basic_total}")
    print(f"  有PE值(>0): {basic_with_pe}")
    print(f"  PE为0: {basic_zero_pe}")
    print(f"  PE为空/负: {basic_total - basic_with_pe - basic_zero_pe}")
    
    # Daily表PE分布
    daily_total = DB_CONN.daily.count_documents({"index": False})  # 只统计股票，不包括指数
    daily_with_pe = DB_CONN.daily.count_documents({"pe": {"$gt": 0}, "index": False})
    daily_zero_pe = DB_CONN.daily.count_documents({"pe": 0, "index": False})
    daily_no_pe_field = DB_CONN.daily.count_documents({"pe": {"$exists": False}, "index": False})
    
    print(f"\nDaily表(仅股票):")
    print(f"  总记录数: {daily_total}")
    print(f"  有PE值(>0): {daily_with_pe}")
    print(f"  PE为0: {daily_zero_pe}")
    print(f"  无PE字段: {daily_no_pe_field}")
    print(f"  其他: {daily_total - daily_with_pe - daily_zero_pe - daily_no_pe_field}")


if __name__ == "__main__":
    # 检查PE数据分布
    check_pe_data_distribution()
    
    print("\n" + "="*60)
    
    # 对比PE值（限制100条记录进行测试）
    compare_pe_values(limit=100) 